import { getsysuserinfoapi, getuserinfoapi, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router/index'
// import { reject, resolve } from 'core-js/fn/promise'
const state = {
  // 用户token
  token: getToken() || '',
  // 用户基本资料
  userinfo: {}
}
const mutations = {
  // 设置token
  settoken(state, newtoken) {
    state.token = newtoken
  },
  // 存储用户资料
  setuserinfo(state, newuserinfo) {
    state.userinfo = newuserinfo
  },
  // 清除token
  removetoken(state) {
    removeToken()
    state.token = ''
  },
  // 清除用户资料
  removeuserinfo(state) {
    state.userinfo = {}
  }
}
const actions = {
  // 走登录接口
  async getlogin({ commit }, data) {
    const res = await login(data)
    commit('settoken', res.data)
    setToken(res.data)
    return res
  },
  // 请求接口，拿用户资料
  async getuserinfo({ commit }) {
    const res = await getuserinfoapi()
    // 基于前面的得到的id，来请求头像
    const ress = await getsysuserinfoapi(res.data.userId)
    // 将两个对象进行合并
    const obj = {
      ...res.data,
      ...ress.data
    }

    commit('setuserinfo', obj)
    return obj
  },
  // 退出登录
  logoout({ commit }) {
    commit('removetoken')
    commit('removeuserinfo')
    resetRouter()
    commit('routes/setroutes', [], { root: true })
    commit('settings/resetTheme', [], { root: true })
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
